import 'dart:convert';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:fake_handwriting/Util.dart';
import 'package:fake_handwriting/generated/l10n.dart';
import 'package:fake_handwriting/http/bean/master_bean.dart';
import 'package:fake_handwriting/http/http.dart';
import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_preview/image_preview.dart';

class Square extends StatefulWidget {
  const Square({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => SquarePage();
}

class SquarePage extends State<Square> {
  List<MasterBean?> list=[];
  List<CancelToken>tokens=[];
  @override
  void initState() {
    super.initState();
    init();
  }
  @override
  void dispose() {
    for (var element in tokens) {
      element.cancel();
    }
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child:ListView.builder(itemBuilder:(c,index){
          List paths=json.decode(list[index]!.path.toString());
          return Padding(
            padding: const EdgeInsets.all(10),
            child: InkWell(
              onTap:(){
                List<String>path=[];
                for (String element in paths){
                  path.add(Http.BASE_URL+element);
                }
                openImagesPage(
                  Navigator.of(context),
                  imgUrls: path,
                  index: 0,
                );
              },onLongPress:() async {
              var res = await showDialog(context: context, builder: (context) => SimpleDialog(
                title: Text(S.of(context).pleaseSelect),
                children:[
                  SimpleDialogOption(
                    child:Text(S.of(context).saveToLocal),
                    onPressed: () {
                      Navigator.pop(context, S.of(context).saveToLocal);
                    },
                  ),
                ],
              ));
              if(res==S.of(context).saveToLocal){
                if(await Util.checkPermission(context)){
                  List paths=json.decode(list[index]!.path.toString());
                  paths.forEach((element) async {
                    CancelToken token=CancelToken();
                    tokens.add(token);
                    var response = await Dio().get(Http.BASE_URL+element.toString(), options: Options(responseType: ResponseType.bytes),cancelToken: token);
                    await ImageGallerySaver.saveImage(Uint8List.fromList(response.data), quality: 100, name:"${DateTime.now().millisecondsSinceEpoch}.png");
                  });
                  Util.toast(S.of(context).saveSucceed);
                }
              }
            },
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(
                    color: Colors.blue
                  ),borderRadius: const BorderRadius.all(Radius.circular(5))
                ),
                child: Padding(
                  padding: const EdgeInsets.all(3),
                  child: Row(children: [
                    Image.network(Http.BASE_URL+paths.first,width: 50,height:50,fit: BoxFit.cover),
                    Padding(
                      padding: const EdgeInsets.only(left: 10),
                      child: Column(children: [
                        Text(list[index]!.title.toString(),style: const TextStyle(
                          fontWeight: FontWeight.w600
                        ),),
                        Text("${S.of(context).from}：${list[index]!.nickname}")
                      ],crossAxisAlignment: CrossAxisAlignment.start,),
                    )
                  ],),
                ),
              ),
            ),
          );
        },itemCount: list.length),
      ),
      appBar: AppBar(
        title:Text(S.of(context).square),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          if(await Http.validateToken()){
            Navigator.pushNamed(context, "create").then((value){
              init();
            });
          }else{
            Navigator.pushNamed(context, "login").then((value) {
              init();
            });
            Util.toast(S.of(context).pleaseLoginAtFirst);
          }
        },
        child: const Icon(Icons.add),
      ),
    );
  }
  Future<void> init() async {
    list=(await Http.get_works())!;
    setState(() {});
  }
}